/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fifa.filters;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Lady
 */
public class SecurityFilter implements Filter {

    public static final String LOGGED_USER = "LOGGED_USER";
    public static final String IS_LOGGED_IN = "IS_LOGGED_IN";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    try {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpSession session = request.getSession(false);

            boolean validUser = false;
            if (session != null) {
                Boolean isLoggenIn =(Boolean) session.getAttribute(IS_LOGGED_IN);
                if(Boolean.TRUE.equals(isLoggenIn)){
                    validUser =true;
                }
            }
            if (validUser){
                chain.doFilter(req, resp);
            }else{
                if (session!=null){
                  session.invalidate();
                }
                response.sendRedirect("/Mundial2014/login.xhtml");
            }
            
        } catch(Exception e){
            Logger.getLogger(SecurityFilter.class.getName()).log(Level.SEVERE,"Error en el filtro de seguridad",e);            
        }        
    }

    @Override
    public void destroy() {
    }

    
}